package com.yyy.common.dao;

import com.yyy.tcc.entity.Account;
import java.math.BigDecimal;
import java.sql.*;

/**
 * 账户数据访问层
 */
public class AccountDao {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/distributed_transaction";
    private static final String USER = "root";
    private static final String PASS = "123456";

    /**
     * 冻结账户金额
     */
    public boolean freezeAmount(String userId, BigDecimal amount) throws SQLException {
        String sql = "UPDATE account SET balance = balance - ?, freeze_amount = freeze_amount + ? " +
                    "WHERE user_id = ? AND balance >= ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setBigDecimal(1, amount);
            stmt.setBigDecimal(2, amount);
            stmt.setString(3, userId);
            stmt.setBigDecimal(4, amount);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 确认转账（解冻并实际扣除金额）
     */
    public boolean confirmTransfer(String fromUserId, String toUserId, BigDecimal amount) throws SQLException {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            conn.setAutoCommit(false);

            // 解冻并扣除转出账户金额
            String deductSql = "UPDATE account SET freeze_amount = freeze_amount - ? " +
                             "WHERE user_id = ? AND freeze_amount >= ?";

            // 增加转入账户金额
            String addSql = "UPDATE account SET balance = balance + ? WHERE user_id = ?";

            try (PreparedStatement deductStmt = conn.prepareStatement(deductSql);
                 PreparedStatement addStmt = conn.prepareStatement(addSql)) {

                deductStmt.setBigDecimal(1, amount);
                deductStmt.setString(2, fromUserId);
                deductStmt.setBigDecimal(3, amount);

                addStmt.setBigDecimal(1, amount);
                addStmt.setString(2, toUserId);

                deductStmt.executeUpdate();
                addStmt.executeUpdate();

                conn.commit();
                return true;
            }
        } catch (SQLException e) {
            if (conn != null) {
                conn.rollback();
            }
            throw e;
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

    /**
     * 取消转账（解冻金额）
     */
    public boolean cancelFreeze(String userId, BigDecimal amount) throws SQLException {
        String sql = "UPDATE account SET balance = balance + ?, freeze_amount = freeze_amount - ? " +
                    "WHERE user_id = ? AND freeze_amount >= ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setBigDecimal(1, amount);
            stmt.setBigDecimal(2, amount);
            stmt.setString(3, userId);
            stmt.setBigDecimal(4, amount);

            return stmt.executeUpdate() > 0;
        }
    }
}
